package com.ly.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 基于角色的登录入口控制器
 * @author ：LY
 * @date ：Created in 2020/11/9 19:14
 * @modified By：
 */
public class LoginUrlEntryPoint extends LoginUrlAuthenticationEntryPoint {
//  private static String userName;
    private static final String API_FREFIX ="/api";
    private static final String API_CODE_403="{\"code\":403}";
    private static final String CONTENT_TYPE="application/json;charset=UTF-8";
    private PathMatcher pathMatcher = new AntPathMatcher();
    private final Map<String,String> authEntryPointMap;

//    public String getUserName() {
//        return userName;
//    }
//
//    public  void setUserName(String userName) {
//        LoginUrlEntryPoint.userName = userName;
//    }

    public LoginUrlEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
        this.authEntryPointMap = new HashMap<>();
        //普通用户登录入口映射
        authEntryPointMap.put("/user/**","/user/login");
        //管理员登录入口映射
        authEntryPointMap.put("/admin/**","/admin/login");
    }


//    public static void main(String[] args) {
//        String uri = "/admin/login";
//        uri.substring(uri.indexOf("/")+1,uri.indexOf("/",uri.indexOf("/")+1));
//        System.out.println(uri);
//    }
    /**
     * 根据请求跳转到指定的页面，父类是默认使用LoginFormUrl
     * @param request
     * @param response
     * @param exception
     * @return
     */
    @Override
    protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        //匹配访问的uri  匹配到了就跳转到相应的登录界面
        String uri = request.getRequestURI().replace(request.getContextPath(),"");
        System.out.println("uri="+getLoginFormUrl());
//        if (uri.equals("/login")||uri.substring(uri.lastIndexOf("/")+1,uri.length()).equals("center"))
//            this.userName = uri.substring(uri.indexOf("/")+1,uri.indexOf("/",uri.indexOf("/")+1));
        for (Map.Entry<String, String> authEntry : this.authEntryPointMap.entrySet()) {
            //匹配uri和map中key的内容
           if( this.pathMatcher.match(authEntry.getKey(),uri)){
               return authEntry.getValue();
           }
        }
        return super.determineUrlToUseForThisRequest(request, response, exception);
    }

    @Override
    public String getLoginFormUrl() {
        return super.getLoginFormUrl();
    }

    /**
     * 如果是api接口就返回json数据，否则返回一般流程
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
      String uri =   request.getRequestURI();
      if (uri.startsWith(API_FREFIX)){
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType(CONTENT_TYPE);
          PrintWriter pw = response.getWriter();
          pw.write(API_CODE_403);
          pw.close();

      }else {
          super.commence(request, response, authException);
      }

    }
}
